package org.jxkj.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jxkj.dto.PmuPointDataDTO;
import org.jxkj.dto.PmuRespDTO;
import org.jxkj.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 查询PMU高频数据的http客户端
 */
public class PmuClient {

    private static Logger LOG = LoggerFactory.getLogger(PmuClient.class);

    private static final String GET = "GET";

    private static final String POST = "POST";

    public static String IP;

    public static int R_PORT;

    /**
     * 获取测点数据（毫秒级，间隔20毫秒）
     * @param pointCode
     * @param startTime
     * @param endTime
     * @return
     */
    public static PmuPointDataDTO getMillisData(String pointCode, long startTime, long endTime) {
        String url = "http://" + IP + ":" + R_PORT + "/api/PmuApiService/dataQuery";
        Map<String, String> params = new HashMap<>(3);
        params.put("codes", pointCode);
        params.put("start", String.valueOf(startTime));
        params.put("end", String.valueOf(endTime));
        try {
            logGetDataRequest(GET, url, JSON.toJSONString(params));
            String content = HttpClientUtils.get(url, params);
            logGetDataResponse(content);
            return returnPointDataList(content, pointCode, startTime, endTime);
        } catch (Exception e) {
            logHttpError(url, JSON.toJSONString(params), e);
            return null;
        }
    }

    /**
     * 最大值
     * @param list
     * @return
     */
    public static Double max(Collection<Double> list) {
        return list.stream().max(Comparator.comparing(i -> i)).orElse(0.0);
    }

    /**
     * 最小值
     * @param list
     * @return
     */
    public static Double min(Collection<Double> list) {
        return list.stream().min(Comparator.comparing(i -> i)).orElse(0.0);
    }

    /**
     * 保留小数点后几位
     * @param v
     * @param n
     * @return
     */
    public static Double round(Double v, int n) {
        BigDecimal bd = new BigDecimal(v);
        bd = bd.setScale(n, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    /**
     * 结果解析
     * @param content
     * @param pointCode
     * @param startTime
     * @param endTime
     * @return
     */
    private static PmuPointDataDTO returnPointDataList(String content, String pointCode, long startTime, long endTime) {
        JSONArray jsonArray = JSONObject.parseArray(content);
        PmuRespDTO pmuRespDTO = jsonArray.getObject(0, PmuRespDTO.class);

        PmuPointDataDTO pmuDTO = new PmuPointDataDTO(startTime, endTime);
        pmuDTO.setPointCode(pointCode);
        List<PmuRespDTO.DataDTO> dataList = pmuRespDTO.getData();
        for (PmuRespDTO.DataDTO obj : dataList) {
            Long beginTs = obj.getTs();
            Integer interval = obj.getInterval();
            List<Double> data = obj.getData();
            for (Double value : data) {
                pmuDTO.addData(beginTs, value);
                beginTs += interval;
            }
        }
        return pmuDTO;
    }

    /**
     * 打印请求日志
     *
     * @param url
     * @param params
     */
    private static void logGetDataRequest(String method, String url, String params) {
        LOG.info("发送Http请求. method={}, url={}, params={}", method, url, params);
    }

    /**
     * 打印响应结果
     *
     * @param response
     */
    private static void logGetDataResponse(String response) {
        LOG.info("获取Http响应结果.");
        LOG.debug("获取Http响应结果. response={}", response);
    }

    /**
     * 打印Http错误日志
     *
     * @param url
     * @param params
     * @param e
     */
    private static void logHttpError(String url, String params, Exception e) {
        LOG.error("Http请求发生异常. url={}, params={}", url, params);
        LOG.error("", e);
    }
}
